﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using HKEA.CMS.Core.BLL;
using HKEA.CMS.Core.Models;
using HKEA.CMS.Core.Utility;
using HKEA.CMS.Core.BLL.Tbl;
using HKEA.CMS.Core.BLL.Mtbl;
using HKEA.CMS.Core.BLL.App;
using System.Transactions;

namespace WebApplication
{
    public partial class M_MainMarket : BasePage
    {
        private static tblCustomer entCust = null;
        int UID=0;
        #region 实例化 tblCust_Market        
        tblCust_MarketBLL bll_Tbl = tblCust_MarketBLL.GetInstance();
        tblCust_Market tmp_Tbl = new tblCust_Market();
        List<tblCust_Market> listTblCustMarket = new List<tblCust_Market>();       
        #endregion

        #region 实例化 app_tblCust_MarketBLL
        app_tblCust_MarketBLL bll_App = app_tblCust_MarketBLL.GetInstance();
        app_tblCust_Market tmp_App = new app_tblCust_Market();
        List<app_tblCust_Market> listAppCustMarket = new List<app_tblCust_Market>();
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                UID = GetEnt();
                if (UID <= 0)
                {
                    usermeg.Visible = false;
                    SetNoOption();
                    lblMeg.Text = ResourceManage.GetResourceString("msg200002");
                }
                else
                {
                    usermeg.Visible = true;
                    entCust = new tblCustomer();
                    tblCustomerBLL bll = tblCustomerBLL.GetInstance();
                    entCust.CustomerUID = UID;
                    entCust = bll.GetEntity(entCust);
                }
                Band_All();
            }
        }
        #region 7个大洲 的国家绑定 为了降低程序的可读性和维护性，一个个绑定(损失了程序的复用性)，也是为了客户以后提出新的想法，往细里改做铺垫
        /// <summary>
        /// 绑定所有大洲的所有国家
        /// </summary>
        private void Band_All()
        {
            Band_1(); Band_2(); Band_3(); Band_4(); Band_5(); Band_6(); Band_7();

            //把值绑定到 checkboxlist里
            if (entCust != null)
                GetValueBindlist(entCust.CustomerUID);
        }

        /// <summary>
        /// 绑定亚洲的国家
        /// </summary>
        private void Band_1()
        {
            mtblCountry ent = new mtblCountry();
            ent.AreaUID = 1;
            List<mtblCountry> tmp_list = new List<mtblCountry>();
            tmp_list = mtblCountryBLL.GetInstance().GetListByENT(ent);

            for (int i = 0; i < tmp_list.Count(); i++)
                tmp_list[i].LastModifyBy = tmp_list[i].Country_Eng + " " + tmp_list[i].Country_Chi;

            CheckBoxList2.DataSource = tmp_list;
            CheckBoxList2.DataTextField = "LastModifyBy";
            CheckBoxList2.DataValueField = "CountryUID";
            CheckBoxList2.DataBind();
        }

        /// <summary>
        /// 绑定中东的国家
        /// </summary>
        private void Band_2()
        {
            mtblCountry ent = new mtblCountry();
            ent.AreaUID = 2;
            List<mtblCountry> tmp_list = new List<mtblCountry>();
            tmp_list = mtblCountryBLL.GetInstance().GetListByENT(ent);

            for (int i = 0; i < tmp_list.Count(); i++)
                tmp_list[i].LastModifyBy = tmp_list[i].Country_Eng + " " + tmp_list[i].Country_Chi;

            CheckBoxList5.DataSource = tmp_list;
            CheckBoxList5.DataTextField = "LastModifyBy";
            CheckBoxList5.DataValueField = "CountryUID";
            CheckBoxList5.DataBind();
        }

        /// <summary>
        /// 绑定澳洲的国家
        /// </summary>
        private void Band_3()
        {
            mtblCountry ent = new mtblCountry();
            ent.AreaUID = 3;
            List<mtblCountry> tmp_list = new List<mtblCountry>();
            tmp_list = mtblCountryBLL.GetInstance().GetListByENT(ent);

            for (int i = 0; i < tmp_list.Count(); i++)
                tmp_list[i].LastModifyBy = tmp_list[i].Country_Eng + " " + tmp_list[i].Country_Chi;

            CheckBoxList3.DataSource = tmp_list;
            CheckBoxList3.DataTextField = "LastModifyBy";
            CheckBoxList3.DataValueField = "CountryUID";
            CheckBoxList3.DataBind();
        }

        /// <summary>
        /// 绑定非洲的国家
        /// </summary>
        private void Band_4()
        {
            mtblCountry ent = new mtblCountry();
            ent.AreaUID = 4;
            List<mtblCountry> tmp_list = new List<mtblCountry>();
            tmp_list = mtblCountryBLL.GetInstance().GetListByENT(ent);

            for (int i = 0; i < tmp_list.Count(); i++)
                tmp_list[i].LastModifyBy = tmp_list[i].Country_Eng + " " + tmp_list[i].Country_Chi;

            CheckBoxList1.DataSource = tmp_list;
            CheckBoxList1.DataTextField = "LastModifyBy";
            CheckBoxList1.DataValueField = "CountryUID";
            CheckBoxList1.DataBind();
        }

        /// <summary>
        /// 绑定北美洲的国家
        /// </summary>
        private void Band_5()
        {
            mtblCountry ent = new mtblCountry();
            ent.AreaUID = 5;
            List<mtblCountry> tmp_list = new List<mtblCountry>();
            tmp_list = mtblCountryBLL.GetInstance().GetListByENT(ent);

            for (int i = 0; i < tmp_list.Count(); i++)
                tmp_list[i].LastModifyBy = tmp_list[i].Country_Eng + " " + tmp_list[i].Country_Chi;

            CheckBoxList6.DataSource = tmp_list;
            CheckBoxList6.DataTextField = "LastModifyBy";
            CheckBoxList6.DataValueField = "CountryUID";
            CheckBoxList6.DataBind();
        }

        /// <summary>
        /// 绑定南美洲的国家
        /// </summary>
        private void Band_6()
        {
            mtblCountry ent = new mtblCountry();
            ent.AreaUID = 6;
            List<mtblCountry> tmp_list = new List<mtblCountry>();
            tmp_list = mtblCountryBLL.GetInstance().GetListByENT(ent);

            for (int i = 0; i < tmp_list.Count(); i++)
                tmp_list[i].LastModifyBy = tmp_list[i].Country_Eng + " " + tmp_list[i].Country_Chi;

            CheckBoxList7.DataSource = tmp_list;
            CheckBoxList7.DataTextField = "LastModifyBy";
            CheckBoxList7.DataValueField = "CountryUID";
            CheckBoxList7.DataBind();
        }

        /// <summary>
        /// 绑定欧洲的国家
        /// </summary>
        private void Band_7()
        {
            mtblCountry ent = new mtblCountry();
            ent.AreaUID = 7;
            List<mtblCountry> tmp_list = new List<mtblCountry>();
            tmp_list = mtblCountryBLL.GetInstance().GetListByENT(ent);

            for (int i = 0; i < tmp_list.Count(); i++)
                tmp_list[i].LastModifyBy = tmp_list[i].Country_Eng + " " + tmp_list[i].Country_Chi;

            CheckBoxList4.DataSource = tmp_list;
            CheckBoxList4.DataTextField = "LastModifyBy";
            CheckBoxList4.DataValueField = "CountryUID";
            CheckBoxList4.DataBind();
        }        

        /// <summary>
        /// 取到国家的id值绑定到 CheckBoxList里
        /// </summary>
        /// <param name="listCust_Market"></param>
        /// <param name="cbl"></param>
        private void GetValueBindlist(int CustomerUID)
        {
            tmp_App = new app_tblCust_Market();
            if (CustomerUID > 0)
            {
                #region 初始化listAppCustMarket
                tmp_App.CustomerUID = entCust.CustomerUID;
                tmp_App.Deleted = -1;
                listAppCustMarket = bll_App.GetListByENT(tmp_App).ToList();

                tmp_Tbl.CustomerUID = CustomerUID;
                tmp_Tbl.Deleted = Constant.IsDelete.no;
                listTblCustMarket = bll_Tbl.GetListByENT(tmp_Tbl).ToList();
                #endregion

                List<int> tmpList = new List<int>();
                for (int i = 0; i < listTblCustMarket.Count(); i++)
                {
                    int Count = listAppCustMarket.Where(a => a.CountryUID == listTblCustMarket[i].CountryUID).Count();
                    if (Count == 0)
                    {
                        tmpList.Add(Convert.ToInt32(listTblCustMarket[i].CountryUID.ToString()));
                    }
                }
                foreach (app_tblCust_Market item in listAppCustMarket)
                {
                    if (item.Deleted == 0)
                    {
                        tmpList.Add(Convert.ToInt32(item.CountryUID.ToString()));
                    }
                }

                CheckBoxList[] cbls = { CheckBoxList1, CheckBoxList2, CheckBoxList3, CheckBoxList4, CheckBoxList5, CheckBoxList6, CheckBoxList7 };



                foreach (CheckBoxList cbl in cbls)
                {
                    if (cbl != null)
                    {
                        for (int i = 0; i < tmpList.Count(); i++)
                        {
                            for (int j = 0; j < cbl.Items.Count; j++)
                            {
                                if (cbl.Items[j].Value == tmpList[i].ToString())
                                {
                                    cbl.Items[j].Selected = true;
                                    HiddenField_val.Value += cbl.Items[j].Value + ",";
                                }
                            }
                        }
                    }
                }
                
            }
        }
        #endregion

        protected void LbtnSave_Click(object sender, EventArgs e)
        {
            #region 保存方案            
            //1:如果App_MainMarket没有包含当前Customer的修改数据,当用户修改后获取当前勾选的数据新增到App_MainMarket表中
            //2:如果App_MainMarket已经有Customer的数据存在,则在分3个步骤 
            //2-> 1)对比当前勾选是否已经存在,若存在,从源表中获取数据添加到Save方法  2)如果没有,表示新数据,作为新纪录添加到Save方法 3)表中存在,但是当前没有勾选,记录到unselectd中;
            #endregion
            #region 计算App_Main_Market是否包含当前Custome的数据
            entCust = new tblCustomer();
            tblCustomerBLL bll = tblCustomerBLL.GetInstance();
            entCust.CustomerUID = GetEnt();
            entCust = bll.GetEntity(entCust);
            //并且定义一个暂时的List<app_tblCust_Market>存放当前勾选的国家的数据
            List<app_tblCust_Market> tmpApplist = new List<app_tblCust_Market>(); 
            tmp_App.CustomerUID = entCust.CustomerUID;
            listAppCustMarket = bll_App.GetListByENT(tmp_App);
            var tmpAppList = bll_App.GetListByENT(tmp_App).Select(a=>a.CountryUID).ToList() ;
            tmp_Tbl.CustomerUID=entCust.CustomerUID;
            var tmpTbllist=bll_Tbl.GetListByENT(tmp_Tbl).Select(a=>a.CountryUID).ToList();
            #endregion

            if (entCust != null)
            {
                int custUID = entCust.CustomerUID;
                List<int> unselectd_uid = new List<int>(); //未被选中的
                CheckBoxList[] chls = { CheckBoxList1, CheckBoxList2, CheckBoxList3, CheckBoxList4, CheckBoxList5, CheckBoxList6, CheckBoxList7 };
                foreach (CheckBoxList cbl in chls)
                {
                    if (cbl != null)
                    {
                        for (int i = 0; i < cbl.Items.Count; i++)
                        {
                            if (cbl.Items[i].Selected) //勾选的数据
                            {
                                tmp_App = new app_tblCust_Market();
                                int item = Convert.ToInt32(cbl.Items[i].Value);
                                var resuleTbl = listTblCustMarket.Where(a => a.CountryUID == item && a.CustomerUID == custUID).ToList();
                                var resuleApp = listAppCustMarket.Where(a => a.CountryUID == item && a.CustomerUID == custUID).ToList();

                                if (resuleApp.Count() > 0)
                                { // 2 -> 1)
                                    foreach (app_tblCust_Market C in resuleApp)
                                    {
                                        tmp_App.CustMarketUID = C.CustMarketUID;
                                        tmp_App.CustomerUID = C.CustomerUID;
                                        tmp_App.CountryUID = C.CountryUID;
                                        tmp_App.Deleted = Constant.IsDelete.no;
                                    }
                                }
                                else if (resuleApp.Count() == 0 && resuleTbl.Count() > 0) //App_没有当前Customer数据,从Tbl取出新增  1
                                {
                                    foreach (tblCust_Market C in resuleTbl)
                                    {
                                        tmp_App.CustMarketUID = C.CustMarketUID;
                                        tmp_App.CustomerUID = C.CustomerUID;
                                        tmp_App.CountryUID = C.CountryUID;
                                        tmp_App.Deleted = Constant.IsDelete.no;
                                    }
                                }
                                else //新增数据 2 -> 2)
                                {
                                    tmp_App.CustMarketUID = 0;
                                    tmp_App.CustomerUID = custUID;
                                    tmp_App.CountryUID = item;
                                    tmp_App.Deleted = Constant.IsDelete.no;
                                }
                                tmpApplist.Add(tmp_App);
                            }
                            else  //删除的数据 2->3)
                            {
                                int item = Convert.ToInt32(cbl.Items[i].Value);
                                int tmpApp = tmpAppList.Where(a => a.Value == item).Count();
                                int tmptbl = tmpTbllist.Where(a => a.Value == item).Count();
                                if (tmpApp > 0 | tmptbl > 0)
                                {
                                    unselectd_uid.Add(item);
                                }
                            }
                        }
                    }
                }
                TransactionOptions sptions = new TransactionOptions();
                sptions.Timeout = new TimeSpan(0, 5, 0);
                sptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, sptions))
                {
                    _save(tmpApplist, custUID);
                    _delete(unselectd_uid, custUID);
                    WriteToLog();
                    try
                    {
                        scope.Complete();
                        lblMeg.Text = ResourceManage.GetResourceString("msg200004");
                    }
                    catch (Exception ex)
                    {
                        lblMeg.Text = ResourceManage.GetResourceString("msg200003");
                    }
                }
            }
            else {
                LbtnSave.Enabled = false;
                lblMeg.Text = ResourceManage.GetResourceString("msg400004");
            }
        }

        private void _save(List<app_tblCust_Market> listCountry, int custUID)
        {
            #region 定义一个listAppCustMarket暂时的app_tblCust_Market新实例,如果有,存放当前CustomeUID标记的数据
            listAppCustMarket = new List<app_tblCust_Market>();
            tmp_App = new app_tblCust_Market();
            tmp_App.CustomerUID = custUID;
            tmp_App.Deleted = -1;
            listAppCustMarket = bll_App.GetListByENT(tmp_App);  //包含了Deleted=1的数据
            listTblCustMarket = new List<tblCust_Market>();
            tmp_Tbl = new tblCust_Market();
            tmp_Tbl.CustomerUID = custUID;
            tmp_Tbl.Deleted = 0;
            listTblCustMarket = bll_Tbl.GetListByENT(tmp_Tbl);
            #endregion

            //判断App_tblCustMarket表是否有对应CustomeUID的数据
            //1.如果没有就直接新增到表中

            for (int i = 0; i < listCountry.Count(); i++)
            {
                int CountApp = listAppCustMarket.Where(a => a.CountryUID == listCountry[i].CountryUID).Count();
                int CountTbl = listTblCustMarket.Where(a => a.CountryUID == listCountry[i].CountryUID).Count();

                if (CountApp <= 0 && CountTbl <= 0)
                {
                    listCountry[i].Deleted = Constant.IsDelete.no;
                    AddItem(listCountry[i] as app_tblCust_Market, custUID);
                }
                else if (CountApp == 1)
                {
                    var val = listAppCustMarket.Where(a => a.CountryUID == listCountry[i].CountryUID).ToList();
                    int tamp = val.Where(a => a.Deleted == Constant.IsDelete.yes).Count();
                    if (tamp == 1)
                    {
                        DeleteItem(listCountry[i] as app_tblCust_Market, custUID);
                    }
                }
            }
        }

        private void _delete(List<int> listCountry, int custUID)
        {
            #region
            List<app_tblCust_Market> Apptmplist = bll_App.GetListByENT(tmp_App);
            List<tblCust_Market>Tbltmplist = new List<tblCust_Market>();
            tmp_Tbl.CustomerUID = custUID;
            tmp_Tbl.Deleted = Constant.IsDelete.no;
            Tbltmplist = bll_Tbl.GetListByENT(tmp_Tbl);
            #endregion
            for (int i = 0; i < listCountry.Count(); i++)
            {
                #region
                tmp_App = new app_tblCust_Market();
                tmp_App.CustomerUID = custUID;
                tmp_App.CountryUID = listCountry[i];
                #endregion
                int CountApp = Apptmplist.Where(a => a.CountryUID == listCountry[i]).Count();
                int CountTbl = Tbltmplist.Where(a=>a.CountryUID==listCountry[i]).Count();
                if (CountApp == 1 && CountTbl == 0) {
                    DeleteItem(tmp_App,custUID);
                }
                else if (CountApp == 0 && CountTbl == 1)
                {
                    var items = Tbltmplist.Where(a => a.CountryUID == listCountry[i]).ToList();
                    foreach (tblCust_Market item in items)
                    {
                        tmp_App.CustMarketUID = item.CustMarketUID;
                        tmp_App.Deleted = Constant.IsDelete.yes;
                        AddItem(tmp_App, custUID); //根据需求,需要记录用户的操作日志,所以数据都不能删除
                    }
                }
            }
        }

        protected void LbtnQuit_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/M_MainMarket.aspx");
        }

        /// <summary>
        ///  member修改了记录,临时记录将会添加到App_表中
        /// </summary>
        /// <param name="item"></param>
        /// <param name="custUID"></param>
        protected void AddItem(app_tblCust_Market item, int custUID)
        {
            app_tblCust_Market tmp = new app_tblCust_Market();
            tmp.CustMarketUID = item.CustMarketUID;
            tmp.CustomerUID = custUID;
            tmp.CountryUID = item.CountryUID;
            tmp.Deleted = item.Deleted;
            tmp.LastModifyBy = Session[Constant.SessionName.Manage] == null ? "system" : (Session[Constant.SessionName.Manage] as tblUser).User_Name.Trim();
            bll_App.InsertENT(tmp);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="item"></param>
        /// <param name="custUID"></param>
        protected void UpDateItem(app_tblCust_Market item, int custUID) {
            app_tblCust_Market tmp = new app_tblCust_Market();
            tmp.CustomerUID = custUID;
            tmp.CountryUID = item.CountryUID;
            tmp.Deleted = item.Deleted;
            tmp.LastModifyBy = Session[Constant.SessionName.Manage] == null ? "system" : (Session[Constant.SessionName.Manage] as tblUser).User_Name.Trim();
            bll_App.UpdateENT(tmp);
        }

        /// <summary>
        /// 删除临时表的记录
        /// </summary>
        /// <param name="item"></param>
        /// <param name="Cuid"></param>
        protected void DeleteItem(app_tblCust_Market item,int Cuid) { 
            app_tblCust_Market tmp=new app_tblCust_Market();
            tmp.CustomerUID = Cuid;
            tmp.CountryUID = item.CountryUID;
            bll_App.DeleteENT(tmp);
        }

        /// <summary>
        /// 
        /// </summary>
        private void SetNoOption()
        {
            LbtnSave.Enabled = false;
            lblMeg.Text = ResourceManage.GetResourceString("msg200001");
        }

        protected void WriteToLog()
        {
            string LoginName = tblCust_WebLoginBLL.GetInstance().GetENT(GetMemberLoginUID()).LoginName.ToString();
            string addlog = string.Empty;
            string dellog = string.Empty;
            mtblCountry entCountry = new mtblCountry();
            List<mtblCountry> list = mtblCountryBLL.GetInstance().GetListByENT(entCountry);
            string[] add = HiddenFiled_add.Value.Split(',');
            string[] delete = HiddenFiled_del.Value.Split(',');
            if (add.Length >1 | delete.Length >1)
            {
                for (int i = 0; i < add.Length - 1; i++)
                {
                    var result = list.Where(a => a.CountryUID == Convert.ToInt32(add[i])).Select(p => p).ToList();
                    foreach (mtblCountry item in result)
                    {
                        addlog += item.Country_Eng + ",";
                    }
                }
                for (int i = 0; i < delete.Length - 1; i++)
                {
                    var result = list.Where(a => a.CountryUID == Convert.ToInt32(delete[i])).Select(p => p).ToList();
                    foreach (mtblCountry item in result)
                    {
                        dellog += item.Country_Eng + ",";
                    }
                }
                if (addlog.Length > 1)
                    addlog = " Add " + addlog.Substring(0, addlog.Length - 1);
                else
                    addlog = "";
                if (dellog.Length > 1)
                    dellog = " Delete " + dellog.Substring(0, dellog.Length - 1);
                else
                    dellog = "";

                tblHistory entlog = new tblHistory();
                Literal CompanyName = usermeg.FindControl("ltlCompanyName_eng") as Literal;
                entlog.HistoryCatUID = 2;
                entlog.HistoryTypeUID = 24;
                entlog.CustomerUID = GetEnt();
                entlog.Cust_MemberUID = 0;
                entlog.ContactPersonUID = 0;
                entlog.History_Detail = LoginName + " {"+CompanyName.Text+"}{MainMarket}" + addlog +  dellog;
                entlog.LastModifyBy = LoginName;
                int tal = tblHistoryBLL.GetInstance().InsertENT(entlog);
            }
        }
    }
}